const User = require('../model/userModel');
const catchAsync = require('../utils/catchAsync');
const AppError = require("../utils/appError");
const factory = require("./handleFactory");
const filterObj = (obj, ...allowedFields)=>{
    const newObj = {};
    Object.keys(obj).forEach(el =>{
        if(allowedFields.includes(el)){
            newObj[el] = obj[el]
        }
    })
    return newObj
}

exports.getAllUser =catchAsync(async(req, res) => {
    const user = await User.find();

    // 发送回复
    res.status(200).json({
        status: 'success',
        results: user.length,
        data: {
            user
        }
    })
})
exports.updateMe =catchAsync( async(req,res,next)=>{
    // 创建错误
     if(req.body.password || req.body.passwordConfirm){
        return next(new AppError("这不是拿来改密码的接口 "))
     }
     // 更新用户文档
     // 并不需要用户的所有字段 需要过滤字段
     const filteredBody = filterObj(req.body,"name","email");
     // 更新文档
     const updatedUser = await User.findByIdAndUpdate(req.user.id, filteredBody,{
        new:true,
        runValidators:true
     })
     res.status(200).json({
        status:'success',
        data:{
            user:updatedUser
        }
     })
})

exports.deleteMe = catchAsync(async(req,res,next)=>{
    await User.findByIdAndUpdate(req.user.id,{active:false});
    
    res.status(204).json({
        status:'success',
        data:null
    })
})
exports.getMe = (req,res,next) =>{
    req.params.id = req.user.id;
    console.log('不会吧')
    next();
}
exports.getUser = factory.getOne(User);
exports.createUser = (req, res) => {
    console.log(req.requestTime);
    res.status(500).json({
        status: 'error',
        message: "this route is not yet defined!"
    })
}
exports.updateUser = factory.updateOne(User);
// 并不包含修改密码
exports.deleteUser = factory.deleteOne(User);